import ApiBase from "@/api/base";
import useRequest from "./useRequest";
import { shallowRef } from "vue";
import setting from "@/utils/setting";
import { useStorage } from "@vueuse/core";

let storeCategoryMap: any = new Map();
let hadLoaded = false;

const transToMap = (list: any[]) => {
  if (list?.length > 0) {
    list.forEach((item) => {
      storeCategoryMap.set(item.id, item);
      transToMap(item.children);
    });
  }
};

const useCategory = () => {
  const list = useStorage<any[]>("Merchant_Category", []);
  const map = shallowRef();

  const getData = async () => {
    const { data } = await useRequest(
      setting.requestHost + ApiBase.getCategoryTree
    );

    list.value = data.value.list;
    transToMap(list.value);
    map.value = storeCategoryMap;
  };

  // 初始化
  if (!map.value) {
    if (storeCategoryMap.size == 0) {
      transToMap(list.value);
    }

    map.value = storeCategoryMap;
  }

  // 刷新一次
  if (!hadLoaded) {
    getData();
  }

  return {
    list,
    map,
  };
};

export default useCategory;
